import { Form, Select, Button, Col, Row, Tree  } from 'antd'
import { useState, useEffect } from 'react'
import { forwardRef, useImperativeHandle } from 'react'
import { selectedNode } from '@/store/redisStore'
import { redisAll, redisConnect } from '@/api/sharing/redis'
import { ModalForm } from "@ant-design/pro-components";
import AddConnetionForm from "./AddConnetionForm";

const LeftPanel = forwardRef(({ style }, ref) => {
  const { setNode } = selectedNode()
  const [form] = Form.useForm()
  const [selectedKey, setSelectedKey] = useState([])
  const [treeData, setTreeData] = useState([])
  const [links, setlinks] = useState([])
  useImperativeHandle(ref, () => ({
    validateFields: form.validateFields,
    getFieldsValue: form.getFieldsValue,
    setFieldsValue: form.setFieldsValue,
  }))
  
  /* 请求方法 */
  const methodOptions = [
    { label: 'GET', value: 'GET' },
    { label: 'POST', value: 'POST' }
  ]
  
  useEffect(() => {
    redisAll().then(res => {
      setlinks(res.result.map(item => ({ label: item.name, value: item.id })))
    });
  }, [setlinks]);

  // const {
  //   data: links
  // } = useQuery({
  //   queryKey: [],
  //   queryFn: () => {
  //     return redisAll().then((res) => {
  //       return res.result.map(item => ({ label: item.name, value: item.id }))
  //     })
  //   },
  //   staleTime: 0,
  //   placeholderData: keepPreviousData,
  // })

  // redisAll().then(res => {
  //   console.log(res);
  //   const data = res.result.map(item => ({ label: item.name, value: item.id }))
  //   // setlinks(data)
  // }) 

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    setNode(selectedKeys[0])
  };

  /* 删除操作 */
  const tableDelete = (id) => {
    let data = form.getFieldValue('requestParams') || []
    const newData = data.filter((item) => item.id !== id)
    form.setFieldValue('requestParams', newData)
  }
  /* 批量删除操作 */
  const handleDelete = () => {
    const data = form.getFieldValue('requestParams') || []
    const newData = data.filter((item) => !selectedRowKeys.includes(item.id))
    form.setFieldValue('requestParams', newData)
    setSelectedRowKeys([])
  }
  /* 生成随机路由 */
  const addRoute = (e) => {
    const route = ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16))
    form.setFieldValue('autoRoute', route)
  }

  const onSelectChange = (key) => {
    console.log(key);
    setSelectedKey(key)
  }
  /* 添加操作 */
  const toConnect = () => {
    redisConnect({id: selectedKey}).then(res => {
      const data = Object.keys(res.result).map((attr, index) => {
        return {
          title: `DB${index}(${res.result[attr]})`,
          key: index.toString()
        }
      })
      setTreeData(data)
    })
  }
  const updateTreeData = (list, key, children) => {
    return list && list.map(node => {
      if (node.key === key) {
        console.log(node, '----', Object.assign(Object.assign({}, node), { children }));
        
        return Object.assign(Object.assign({}, node), { children });
      }
      if (node.children) {
        return Object.assign(Object.assign({}, node), {
          children: updateTreeData(node.children, key, children),
        });
      }
      return node;
    });
  }
    const onLoadData = ({ key, children }) =>
      new Promise(resolve => {
        if (children) {
          resolve();
          return;
        }
        redisConnect({ id: selectedKey, database: key }).then(res => {
          console.log(res); // 连接成功
          let arr = []
          Object.keys(res.result).forEach((item, index) => {
            const newArr = (res.result[item] || []).map((subItem) => {
              return {
                title: subItem,
                key: subItem,
                tag: item,
                isLeaf: true
              } 
            })
            arr = arr.concat(newArr)
          })
          setTreeData(origin =>
            updateTreeData(origin, key, arr),
          );
            resolve();
        })
        // setTimeout(() => {
        //   setTreeData(origin =>
        //     updateTreeData(origin, key, [
        //       { title: 'Child Node', key: `${key}-0` },
        //       { title: 'Child Node', key: `${key}-1` },
        //     ]),
        //   );
        //   resolve();
        // }, 1000);
      });
  // 新增
  const handleConnectionSave = (values) => {
    if (values.id) {
      return dataSubjectEdit(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return dataSubjectAdd(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  return (
    <div>
      <Row gutter={[10, 10]}>
        <Col span={20}>
          <Select style={{ width: '100%' }} placeholder="请选请求方式" options={links} onChange={onSelectChange}></Select>
        </Col>
        <Col span={4}>
          <Button style={{ width: '80px' }} type="primary" onClick={toConnect}>
            连接
          </Button>
        </Col>
        <Col span={20}>
          <p style={{ lineHeight: '32px', paddingLeft: '10px' }}>192.168.1.1:6379</p>
        </Col>
        <Col span={4}>
          <ModalForm
            width={'400px'}
            trigger={<Button className="ml-2" type="primary">新增连接</Button>}
            title="新增连接"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleConnectionSave}
            grid={true}
            initialValues={{
              status: '0'
            }}
          >
            <AddConnetionForm />
          </ModalForm>
          {/* <Button style={{ width: '80px' }}> */}
        </Col>
      </Row>
      <Tree
        loadData={onLoadData}
        treeData={treeData}
      />
    </div>
  )
})

export default LeftPanel
